package com.lee.dutylower.view.setting;


import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;


import com.lee.dutylower.MyApplication;
import com.lee.dutylower.R;
import com.lee.dutylower.db.greenEntity.Soldier;
import com.lee.dutylower.db.greenEntity.SoldierSentry;
import com.lee.dutylower.db.greendao.SoldierDao;
import com.lee.dutylower.db.greendao.SoldierSentryDao;
import com.lee.dutylower.domain.SoldierInUseEnum;
import com.lee.dutylower.utils.ToastUtils;
import com.lee.dutylower.view.BaseFragment;
import com.lee.dutylower.view.detail.SoldierDetailFragment;

import java.util.List;

/**
 * Created by lijie on 2017/4/28.
 */
public class SoldierSettingFragment extends BaseFragment {
    private TextView tvSettingName;
    private TextView tvSettingListName;
    private ListView lvData;

    public Button btnAdd;
    public Button btnSave;
    public Button btnEdit;

    private List<Soldier> values;
    private Soldier currentSoldierDB;

    private MyAdapter myAdapter;
    private int lastPosition = -1;
    //private LinearLayoutManager layoutManager;
    private SoldierDao soldierDao;
    private SoldierSentryDao soldierSentryDao;

    private SoldierDetailFragment detailFragment;

    public SoldierSettingFragment() {
    }


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        lastPosition = -1;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        soldierDao = MyApplication.getApplication().getDaoSession().getSoldierDao();
        soldierSentryDao = MyApplication.getApplication().getDaoSession().getSoldierSentryDao();
        View v = View.inflate(getActivity(), R.layout.fragment_setting,null);
        tvSettingName = (TextView) v.findViewById(R.id.tv_setting_name);
        tvSettingListName = (TextView) v.findViewById(R.id.tv_setting_list_name);

        btnAdd = (Button) v.findViewById(R.id.btn_add_data);
        btnSave = (Button) v.findViewById(R.id.btn_data_save);
        btnEdit = (Button) v.findViewById(R.id.btn_data_edit);

        lvData = (ListView) v.findViewById(R.id.lv_setting_db);

        tvSettingName.setText("人员设置");
        tvSettingListName.setText("所有人");

        values = soldierDao.queryBuilder().build().list();
        myAdapter = new MyAdapter();
        lvData.setAdapter(myAdapter);
        //点击事件监听
        lvData.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                btnSave.setVisibility(View.INVISIBLE);
                btnEdit.setEnabled(true);

                detailFragment = new SoldierDetailFragment();
                lastPosition = position;
                TextView tv = (TextView) view.findViewById(R.id.tv_lv_data);
                tv.setTextSize(20);
                tv.setBackgroundColor(0xFFA36F59);
                myAdapter.notifyDataSetChanged();

                MyAdapter.ViewHolder holder = (MyAdapter.ViewHolder) view.getTag();
                String soldierid = holder.ID.getText().toString();
                Soldier soldierDB = soldierDao.queryBuilder()
                        .where(SoldierDao.Properties.SID.eq(Integer.parseInt(soldierid)))
                        .build().unique();
                currentSoldierDB = soldierDB;
                addFragment(detailFragment,soldierDB,"soldier");

                btnEdit.setVisibility(View.VISIBLE);
            }
        });
        lvData.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                MyAdapter.ViewHolder holder = (MyAdapter.ViewHolder) view.getTag();
                final String sid = holder.ID.getText().toString();
                AlertDialog alert ;
                TextView tv = (TextView) view.findViewById(R.id.tv_lv_data);
                tv.setTextSize(20);
                tv.setBackgroundColor(0xFFA36F59);
                myAdapter.notifyDataSetChanged();
                alert = new AlertDialog.Builder(getActivity())
                        .setTitle("删除")
                        .setMessage("确认删除 数据：" + tv.getText() + "?")
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                soldierDao.deleteByKey(Long.parseLong(sid));
                                values = soldierDao.queryBuilder().build().list();
                                myAdapter.notifyDataSetChanged();
                            }
                        })
                        .setNegativeButton("取消", null)
                        .create();
                alert.show();
                return true;
            }
        });


        //新增数据按钮
        btnAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                lastPosition = -1;
                btnEdit.setEnabled(false);
                btnSave.setVisibility(View.VISIBLE);
                btnSave.setEnabled(true);
                detailFragment = new SoldierDetailFragment();
                addEmptyFragment(detailFragment);
                myAdapter.notifyDataSetChanged();
            }
        });
        //保存数据
        btnSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(detailFragment.isAdd){
                    Soldier nSoldier = new Soldier();
                    //从detailfragment 获取值 插入
                    String name = detailFragment.etName.getText().toString();
                    name = name.trim();
                    if(!"".equals(name)){
                        nSoldier.setSName(name);
                    }else {
                        ToastUtils.showShort(getActivity(),"名称不能为空");
                    }

                    if(detailFragment.squadID != -1){
                        nSoldier.setSquadID(detailFragment.squadID);
                    }else {
                        ToastUtils.showShort(getActivity(),"请选择所属班");
                        return;
                    }
                    if (detailFragment.grade != -1){
                        nSoldier.setGrade(detailFragment.grade);
                    }else {
                        ToastUtils.showShort(getActivity(),"请选择班内职务");
                        return;
                    }
                    nSoldier.setInUse(SoldierInUseEnum.NoUse.getCode());
                    long sid = soldierDao.insert(nSoldier);
                    if(detailFragment.sentryGroup!=null){
                        if (detailFragment.sentryGroup.size()!=0){
                            for (Long aLong : detailFragment.sentryGroup) {
                                soldierSentryDao.insert(new SoldierSentry(null,sid,aLong));
                            }
                        }
                    }else {
                        ToastUtils.showShort(getActivity(),"请选择哨位");
                        return;
                    }
                    ToastUtils.showShort(getActivity(),"插入成功");
                    values = soldierDao.queryBuilder().build().list();
                    myAdapter.notifyDataSetChanged();
                    detailFragment = new SoldierDetailFragment();
                    addEmptyFragment(detailFragment);
                }else {
                    //从detailfragment 获取值 更新到currentSoldierDB
                    String name = detailFragment.etName.getText().toString();
                    name = name.trim();
                    if(!"".equals(name)){
                        currentSoldierDB.setSName(name);
                    }else {
                        ToastUtils.showShort(getActivity(),"名称不能为空");
                    }
                    if(detailFragment.sentryGroup!=null){
                        if (detailFragment.sentryGroup.size()!=0){
                            List<SoldierSentry> ss = soldierSentryDao.queryBuilder()
                                    .where(SoldierSentryDao.Properties.SoldierId.eq(currentSoldierDB.getSID()))
                                    .build().list();
                            soldierSentryDao.deleteInTx(ss);
                            for (Long aLong : detailFragment.sentryGroup) {
                                soldierSentryDao.insert(new SoldierSentry(null,currentSoldierDB.getSID(),aLong));
                            }
                        }
                    }
                    if(detailFragment.squadID != -1){
                        currentSoldierDB.setSquadID(detailFragment.squadID);
                    }
                    if (detailFragment.grade != -1){
                        currentSoldierDB.setGrade(detailFragment.grade);
                    }
                    currentSoldierDB.setInUse(SoldierInUseEnum.NoUse.getCode());
                    //更新入库
                    soldierDao.update(currentSoldierDB);
                    ToastUtils.showShort(getActivity(),"修改成功");
                    values = soldierDao.queryBuilder().build().list();
                    myAdapter.notifyDataSetChanged();
                    btnSave.setVisibility(View.INVISIBLE);
                    Soldier soldierDB = soldierDao.queryBuilder().where(SoldierDao.Properties.SID.eq(currentSoldierDB.getSID())).build().unique();
                    soldierDB.resetSentryGroup();
                    currentSoldierDB = soldierDB;
                    detailFragment = new SoldierDetailFragment();
                    addFragment(detailFragment,soldierDB,"soldier");
                }
                btnEdit.setEnabled(true);
            }
        });

        btnEdit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                btnEdit.setEnabled(false);

                detailFragment = new SoldierDetailFragment();
                addEditFragment(detailFragment,currentSoldierDB,"soldier");

                btnSave.setVisibility(View.VISIBLE);
            }
        });

        return v;
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    class MyAdapter extends BaseAdapter {
        public MyAdapter() {
        }

        @Override
        public int getCount() {
            return values.size();
        }

        @Override
        public Object getItem(int position) {
            return values.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            Soldier soldier = values.get(position);
            if(convertView == null){
                holder = new ViewHolder();
                convertView = View.inflate(getActivity(),R.layout.listview_item,null);
                holder.tv = (TextView) convertView.findViewById(R.id.tv_lv_data);
                holder.ID = (TextView) convertView.findViewById(R.id.tv_lv_id);
                convertView.setTag(holder);
            }else {
                holder = (ViewHolder) convertView.getTag();
            }

            holder.tv.setText(soldier.getSName());
            holder.ID.setText(soldier.getSID()+"");

            if(lastPosition != position){
                holder.tv.setTextSize(16);
                holder.tv.setBackgroundColor(0xFFB38672);
            }else {
                holder.tv.setTextSize(20);
                holder.tv.setBackgroundColor(0xFFA36F59);
            }

            return convertView;
        }

        class ViewHolder{
            TextView tv;
            TextView ID;
        }
    }
}
